package model;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
 * @description : save the information that the user have
 * @param : userName
 * @param : userPass
 * @param : goodCar save the goods message that user bye
 * @param : goodRecord keep records of shopping
 * 
 */
public class User implements Serializable{
	
	private String userName;
	private String userPass;
	private Map<Good, Integer> goodCar = new HashMap<>();
	private Map<Good, Integer> goodRecord = new HashMap<>();
	public Map<Good, Integer> getGoodRecord() {
		return goodRecord;
	}
	public void setGoodRecord(Map<Good, Integer> goodRecord) {
		this.goodRecord = goodRecord;
	}
	public Map<Good, Integer> getGoodCar() {
		return goodCar;
	}
	public void setGoodCar(Map<Good, Integer> goodCar) {
		this.goodCar = goodCar;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getUserPass() {
		return userPass;
	}
	public void setUserPass(String userPass) {
		this.userPass = userPass;
	}
	/**
	 * @description : override hash code function by userName  
	 */
	@Override
	public int hashCode() {
		// TODO Auto-generated method stub
		return userName.hashCode();
	}
	/**
	 * @description : override the equals function  by userName 
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		User other = (User) obj;
		if (!userName.equals(other.userName))
			return false;
		return true;
	}
	/**
	 * @description : add good to shopping cart 
	 * @param : Good good  
	 * @param : Integer number
	 */
	public void add(Good good,Integer number){
		if(goodCar.containsKey(good)){
			goodCar.put(good,goodCar.get(good)+number);
		}else{
			goodCar.put(good, number);
		}
	}
	/**
	 * @description :  add record to goodRecord
	 * @param : Map <Good , Integer> goodCar
	 */
	public void addRecord(Map<Good, Integer> goodCar){
		goodCar.keySet().forEach((good)->{
			int num = goodCar.get(good);
			if(goodRecord.containsKey(good)){
				goodRecord.put(good,goodRecord.get(good)+num);
			}else{
				goodRecord.put(good,num);
			}
		});
	}
	/**
	 * @description : save the user's information 
	 * @param : User user
	 */
	public static void saveUser(User user){
		File file = new File("D:/store/user/"+user.getUserName()+".txt");
		try {
			new ObjectOutputStream(new FileOutputStream(file)).writeObject(user);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
